package com.tools.cleanmaster.ui.base;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.hm.ads.sdk.HmAdsSDK;
import com.hm.base.android.mob.util.network.NetWorkInfoParser;
import com.hm.base.android.ui.AActivity;
import com.tools.ad.util.GARecordUtils;
import com.tools.cleanmaster.BuildConfig;
import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.CleanGAConstant;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.ui.dialog.CommonDialog;
import com.tools.cleanmaster.ui.view.ToastHelper;
import com.tools.cleanmaster.ui.view.header.OnBackStackListener;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.rationale.OverlayRationale;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


@SuppressWarnings("static-access")
public class BaseActivity extends AActivity<CleanApplication> implements OnBackStackListener {
    /**
     * 设置启动的Activity是否需要显示动画
     */
    public static final int POPWINDOW_SHOW_TWICE_INTERVAL = 350;

    private boolean mHasAnimation = true;

    //是否处于可退出状态
    private boolean isExit;
    //是否可以双击退出
    private boolean isExitBy2Click;
    //双击退出提示文字
    private String exitTip;

    private CommonDialog feedbackTipDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        exitTip = getResources().getString(R.string.click_exit_tip);
        isExitBy2Click = false;
        //activity 初始化检查网络状态
        NetWorkInfoParser.isNetConnect(imContext);
    }

    /**
     * 是否显示动画
     */
    protected boolean hasAnimation() {
        return mHasAnimation;
    }

    @Override
    public void finish() {
        super.finish();
        if (hasAnimation()) {
            defaultOverridePendingTransition();
        }
    }

    public void startActivityWithAnim(Intent intent) {
        mHasAnimation = true;
        startActivity(intent);
        defaultOverridePendingTransition();
    }

    public void startActivityForResultWithAnim(Intent intent, int requestCode) {
        mHasAnimation = true;
        startActivityForResult(intent, requestCode);
        defaultOverridePendingTransition();
    }

    /**
     * Warning:已过时标记只是为了警告无法使用此函数进行过场动画；
     * 除非你覆盖此方法，否则永远是默认实现
     * 默认请使用：
     *
     * @see #defaultOverridePendingTransition()
     * 自定义请使用：
     * @see #customPendingTransition(int, int)
     */
    @Deprecated
    @Override
    public final void overridePendingTransition(int enterAnim, int exitAnim) {
        defaultOverridePendingTransition();
    }

    protected final void defaultOverridePendingTransition() {
        super.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    protected final void customPendingTransition(int enterAnim, int exitAnim) {
        super.overridePendingTransition(enterAnim, exitAnim);
    }

    @Override
    public void onBackStack() {
        onBackPressed();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            //CrabSDK.doActivityStart(this);
        }
    }

    @Override
    protected void doOnPause() {
        //CrabSDK.onPause(this);
    }

    @Override
    protected void startMainFrame() {

    }

    @Override
    protected void doOnResume() {
        //CrabSDK.onResume(this);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //CrabSDK.behaviorRecordEvent(ev, this);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onStop() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            //CrabSDK.doActivityStop(this);
        }
        super.onStop();
    }

    private void clearAllCache() {
        imContext.checkForLongLive(true);
    }

    public void doExitClient() {
        // 关闭所有试图
        closeAllActivity();
        try {
            clearAllCache();
        } catch (Exception e) {
            e.printStackTrace();
        }
        HmAdsSDK.getInstance().updateAdConfig();
    }

    protected void setExitBy2Click(boolean isExitBy2Click) {
        this.isExitBy2Click = isExitBy2Click;
    }

    protected boolean exitBy2Click() {
        if (!isExit) {
            isExit = true;
            ToastHelper.create(this, exitTip, Toast.LENGTH_SHORT).show();
            Timer tExit = new Timer();
            tExit.schedule(new TimerTask() {
                public void run() {
                    isExit = false;
                }
            }, 2000);

        } else if (!imContext.getADModule().isOrganicOrOtherChannel() && !imContext.getCleanSharedPrefManager().haveShowedFeedbackDialog()) {
            showFeedbackDialog();

        } else {
            doExitClient();

            return true;
        }

        return false;
    }

    /**
     * 显示反馈对话框
     */
    private void showFeedbackDialog() {
        if (feedbackTipDialog == null) {
            feedbackTipDialog = new CommonDialog(this);
            feedbackTipDialog.setMessage(R.string.feedback_message);
            feedbackTipDialog.setCancelBtn(R.string.feedback_cancel, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    feedbackTipDialog.dismiss();
                    imContext.getCleanSharedPrefManager().showFeedbackDialog();
                    doExitClient();
                }
            });
            feedbackTipDialog.setOkBtn(R.string.feedback_ok, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    feedbackTipDialog.dismiss();
                    imContext.getCleanSharedPrefManager().showFeedbackDialog();
                    GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_CLICK, CleanGAConstant.L_HOME_MENU_FEEDBACK);
                    Intent i = new Intent(Intent.ACTION_SENDTO);
                    i.setData(Uri.parse("mailto:" + BuildConfig.FEEDBACK_MAIL));
                    i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.opda_global_feed));
                    try {
                        startActivity(i);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        feedbackTipDialog.show();
    }

    /**
     * Request permissions.
     *
     * @param permissions {@link #onPermissionGranted(List<String>)}
     *                    {@link #onPermissionDenied(List<String>)}
     */
    protected void requestPermission(String... permissions) {
        AndPermission.with(this)
                .runtime()
                .permission(permissions)
                //.rationale(new RuntimeRationale())
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        onPermissionGranted(permissions);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        onPermissionDenied(permissions);
                    }
                })
                .start();
    }

    protected void onPermissionGranted(List<String> permissions) {

    }

    protected void onPermissionDenied(final List<String> permissions) {
        AndPermission.handleAlwaysDeniedPermission(this, permissions, new AndPermission.SettingPermissionListener() {
            @Override
            public void onCloseSettingPage() {
                comeBackFromSystemSetting(permissions);
            }

            @Override
            public void onCancel() {
                alwaysDeniedStillCancel(permissions);
            }

            @Override
            public void onSetting() {
                alwaysDeniedStillSetting(permissions);
            }
        }, R.style.AlertDialogTheme);
    }

    //申请的权限被用户勾选不在提示,应用自身弹框提示用户
    //该方法为弹框提示 取消 按键回调, 具体业务给调用的activity子类实现
    protected void alwaysDeniedStillCancel(List<String> permissions) {

    }


    //该方法为弹框提示 设置 按键回调
    protected void alwaysDeniedStillSetting(List<String> permissions) {

    }

    //该方法为关闭系统设置页面后的回调
    protected void comeBackFromSystemSetting(List<String> permissions) {

    }

    /**
     * Alert view
     *
     * @param rationale 为Null 则使用 OverlayRationale
     *                  {@link #onOverlayPermissionGranted()}
     *                  {@link #onOverlayPermissionDenied()}
     */
    protected void requestOverlay(@Nullable Rationale<Void> rationale) {
        AndPermission.with(this)
                .overlay()
                .rationale(rationale != null ? rationale : new OverlayRationale())
                .onGranted(new Action<Void>() {
                    @Override
                    public void onAction(Void data) {
                        onOverlayPermissionGranted();
                    }
                })
                .onDenied(new Action<Void>() {
                    @Override
                    public void onAction(Void data) {
                        onOverlayPermissionDenied();
                    }
                })
                .start();
    }

    protected void onOverlayPermissionGranted() {

    }

    protected void onOverlayPermissionDenied() {

    }
}
